package com.cskt.securityproject.service;

import com.cskt.securityproject.entity.Permission;
import com.cskt.securityproject.entity.User;
import com.cskt.securityproject.mapper.PermissionMapper;
import com.cskt.securityproject.mapper.UserMapper;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @description 自定义UserDetailService
 * @date 2023/12/14 14:05
 * @auth mo
 */
@Service
public class MyUserDetailService implements UserDetailsService {

    private static final Logger log = LoggerFactory.getLogger(MyUserDetailService.class);

    @Resource
    private UserMapper userMapper;
    @Resource
    private PermissionMapper permissionMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //调用mapper接口根据用户名查询用户信息
        User user = userMapper.selectUserByUserName(username);
        //判断用户是否存在
        if (ObjectUtils.isEmpty(user)) {
            log.warn("当前用户不存在");
            throw new UsernameNotFoundException("当前用户不存在");
        }
        if (user.getStatus().equals(0)) {
            log.warn("当前用户已被锁定");
            throw new LockedException("当前用户已被锁定");
        }
        //如果以上的异常全部没有，则验证成功
        return new org.springframework.security.core.userdetails.User(username,
                user.getPassword(),
                //把当前登录用户的权限整合进来
                permission(user.getId()));
    }

    /**
     * 根据登录用户id查询用户权限
     *
     * @param userId 当前登录用户id
     * @return 当前登录用户的权限集合
     */
    private Collection<? extends GrantedAuthority> permission(Integer userId) {
        List<Permission> permissions = permissionMapper.selectPermissionById(userId);
        return permissions.stream()
                .map(permission ->new SimpleGrantedAuthority(permission.getPermissionTag()))
                .toList();
    }

}
